<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 房间详情内容 -->
    <div class="container mx-auto px-4 py-8">
      <!-- 房间图片轮播 -->
      <div class="mb-8 rounded-xl overflow-hidden shadow-lg">
        <swiper
            :modules="swiperModules"
            :pagination="{ clickable: true }"
            :autoplay="{ delay: 3000 }"
            class="w-full h-[300px]"
        >
          <swiper-slide v-for="(image, index) in roomImages" :key="index">
            <img
                :src="`${SERVER_ADDR}/upload/${image}`"
                class="w-full h-full object-cover object-center"
                alt="房间图片"
            />
          </swiper-slide>
        </swiper>
      </div>

      <!-- 房间基本信息 -->
      <div class="flex flex-col md:flex-row gap-8 mb-8">
        <!-- 左侧信息 -->
        <div class="md:w-2/3">
          <h1 class="text-3xl font-bold text-gray-800 mb-2">{{ roomInfo.type === 1 ? '标准单人房' : '标准双人房' }} . {{ getRoomWidth(roomInfo.width) }}</h1>
          <div class="flex items-center mb-6">
            <el-icon class="text-yellow-400 mr-1"><Location /></el-icon>
            <span class="text-gray-600">{{ roomInfo.rno }}</span>
          </div>

          <!-- 价格信息 -->
          <div class="bg-white p-6 rounded-xl shadow-sm mb-6">
            <div class="flex items-end mb-4">
              <span class="text-4xl font-bold text-blue-600 mr-2"
              >¥{{ roomInfo.rmoney }}</span
              >
              <span class="text-gray-500">/月</span>
            </div>
            <div class="text-gray-600">
              <span class="mr-4">层高: {{ roomInfo.height }}楼</span>
              <span>朝向: {{ getRoomWidth(roomInfo.width) }}</span>
            </div>
          </div>

          <!-- 设施信息 -->
          <div class="bg-white p-6 rounded-xl shadow-sm mb-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">房间设施</h2>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div
                  v-for="facility in roomInfo.goods"
                  :key="facility.name"
                  class="flex items-center"
              >
                <el-icon class="text-blue-500 mr-2" :class="facility.icon">
                  <component :is="getFacilityIcon(facility.name)" />
                </el-icon>
                <span>{{ facility.name }}</span>
              </div>
            </div>
          </div>

          <!-- 房间描述 -->
          <div class="bg-white p-6 rounded-xl shadow-sm">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">房间描述</h2>
            <p class="text-gray-600 leading-relaxed">
              {{ roomInfo.description }}
            </p>
          </div>
        </div>

        <!-- 右侧预订 -->
        <div class="md:w-1/3">
          <div class="bg-white p-6 rounded-xl shadow-sm sticky top-4">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">选择租期</h2>

            <!-- 租期选择 -->
            <div class="space-y-4 mb-6">
              <div
                  v-for="option in rentOptions"
                  :key="option.value"
                  @click="selectRentOption(option)"
                  :class="{
                  'border-blue-500 bg-blue-50': selectedOption.value === option.value,
                  'border-gray-200 hover:border-blue-300': selectedOption.value !== option.value
                }"
                  class="border rounded-lg p-4 cursor-pointer transition-colors"
              >
                <div class="flex justify-between items-center">
                  <span class="font-medium">{{ option.label }}</span>
                  <span class="text-blue-600 font-semibold">¥{{ option.price }}</span>
                </div>
                <div v-if="option.discount" class="text-sm text-green-500 mt-1">
                  节省 ¥{{ option.discount }}
                </div>
              </div>
            </div>

            <!-- 总价 -->
            <div class="border-t pt-4 mb-6">
              <div class="flex justify-between items-center">
                <span class="text-gray-600">总价</span>
                <span class="text-2xl font-bold text-blue-600">¥{{ totalPrice }}</span>
              </div>
            </div>

            <!-- 预订按钮 -->
            <button
                @click="handleBook"
                class="w-full !rounded-button whitespace-nowrap bg-blue-600 hover:bg-blue-700 text-white py-3 px-4 font-semibold transition-colors"
            >
              立即预订
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部固定按钮 -->
    <div class="fixed bottom-0 left-0 right-0 bg-white shadow-lg py-4">
      <div class="container mx-auto px-4">
        <div class="flex justify-between items-center">
          <div>
            <span class="text-gray-600 mr-4">总价:</span>
            <span class="text-2xl font-bold text-blue-600">¥{{ totalPrice }}</span>
          </div>
          <button
              @click="handleBook"
              class="!rounded-button whitespace-nowrap bg-blue-600 hover:bg-blue-700 text-white py-3 px-8 font-semibold transition-colors"
          >
            立即预订
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="js" setup>
import { ref, computed } from 'vue';
import { Swiper, SwiperSlide } from 'swiper/vue';
import { Pagination, Autoplay } from 'swiper/modules';
import {
  House,
  Location,
  Sunny,
  Watermelon,
  Refrigerator,
  Dish,
  Van,
  OfficeBuilding,
  VideoCamera,
  Lock,
} from '@element-plus/icons-vue';
import {useRoute, useRouter} from "vue-router";
import roomApi from "@/api/admin/roomApi.js";
import occupancyApi from "@/api/user/occupancyApi.js";
import {ElMessage} from "element-plus";

//服务器路径
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
const router = useRouter();
const route  = useRoute();
const swiperModules = [Pagination, Autoplay];

// 房间图片
const roomImages = ref([]);

// 房间信息
const roomInfo = ref({
  name: '阳光大床房 · 朝南',
  location: '北京市朝阳区建国路88号优居公寓3号楼',
  price: 3800,
  area: 35,
  direction: '南',
  status: '空置',
  description:
      '这是一间采光极佳的朝南房间，配备1.8米大床、独立卫浴和简易厨房。房间采用现代简约装修风格，配备全新家具家电，可直接拎包入住。公寓位于CBD核心区，交通便利，周边商业配套齐全。',
  facilities: [
    { name: '空调', icon: Sunny },
    { name: '独立卫浴', icon: Watermelon },
    { name: 'Wi-Fi', icon: Watermelon },
    { name: '冰箱', icon: Refrigerator },
    { name: '简易厨房', icon: Dish },
    { name: '洗衣机', icon: Watermelon },
    { name: '电梯', icon: Van },
    { name: '24小时安保', icon: Lock },
    { name: '门禁系统', icon: OfficeBuilding },
    { name: '监控系统', icon: VideoCamera },
  ],
});

// 租期选项
const rentOptions = ref([
  { label: '1个月', value: 1, price: 3800, discount: 0 },
  { label: '3个月', value: 3, price: 11000, discount: 400 },
  { label: '6个月', value: 6, price: 21000, discount: 1800 },
  { label: '12个月', value: 12, price: 40000, discount: 5600 },
]);

// 选中的租期选项
const selectedOption = ref(rentOptions.value[0]);

// 计算总价
const totalPrice = computed(() => selectedOption.value.price);

// 选择租期
const selectRentOption = (option) => {
  selectedOption.value = option;
};

// 预订处理
const handleBook = () => {
  // 将租期转换成月份 日期是今天
  const monthsToAdd = selectedOption.value.value;
  const startDate = new Date(); // 开始时间：今天
  const endDate = new Date();    // 结束时间：基于租期加上相应月份

  endDate.setMonth(endDate.getMonth() + monthsToAdd);

  let occupancy = {
    roomId: roomInfo.value.rid,
    startTime: formatDate(startDate),
    endTime: formatDate(endDate),
    price: totalPrice.value,
  };
  occupancyApi.insert(occupancy)
      .then(resp => {
        if (resp.code == 10000){
          ElMessage.success({
            message: "预订成功,等待管理员审核",
            duration: 1200,
            onClose: ()=>{
              router.push("/oldroom")
            }
          })
        }
      })
};
// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 获取房间信息
const getRoomInfo = () => {
  let roomId = route.query.id;
  roomApi.selectById(roomId)
      .then(resp => {
        if (resp.code == 10000){
          roomInfo.value = resp.data;
          roomImages.value.push(roomInfo.value.pic);
          // 设置租期和价格
          rentOptions.value.forEach(option => {
            option.price = option.value * resp.data.rmoney;
            option.price = option.price - ((option.value-1) / 100 * option.price) ;
            option.discount = (option.value * resp.data.rmoney) -option.price ;
          })
        }
      })
};
// 获取房间的朝向
const getRoomWidth = (width) => {
  switch (width){
    case 1:
      return '朝南';
    case 2:
      return '朝北';
    case 3:
      return '朝东';
    case 4:
      return '朝西';
    default:
      return '未知';
  }
};
// 获取设施的icon
const getFacilityIcon = (facility) => {
  switch (facility) {
    case '空调':
      return Sunny;
    case '电视':
      return Watermelon;
    case 'WIFI':
      return Watermelon;
    case '电话':
      return Refrigerator;
    case '保险箱':
      return Dish;
    case '吹风机':
      return Watermelon;
    case '浴缸':
      return Van;
    case '迷你吧':
      return Lock;
    case '办公桌':
      return OfficeBuilding;
    case '冰箱':
        return VideoCamera;
  }
}
getRoomInfo();
</script>

<style scoped>
.container {
  max-width: 1200px;
}

/* 确保底部固定按钮不会遮挡内容 */
.min-h-screen {
  padding-bottom: 80px;
}
</style>
